/**
 * @ Description   :  接收用户数据保存到数据库
 * @ Author        :  annyliang
 * @ CreateDate    :  2022/8/6 11:30
 * @ UpdateUser    :  annyliang
 * @ Version       :  v1.0
 */
package controllers

import (
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"github.com/astaxie/beego"
	log "go.uber.org/zap"
	util "learn-api/common/utils"
	"learn-api/constant"
	"learn-api/dao"
	"learn-api/models"
	"strings"
)

// UserController
type UserController2 struct {
	BaseController
}

// @Title Get
// @Success 200 "保存成功"
// @Param   LoginName query string
// @Param   UserName query string
// @Param   Phone query string
// @Param   Sign query string
// @Failure 400 Param check failed
// @Failure 500 post UserDataModel common error
// @router / [Get]
func (c *UserController2) Get() {
	rspm := make(map[string]interface{})
	loginName := c.GetString("LoginName")
	userName := c.GetString("UserName")
	phone := c.GetString("Phone")
	sign := c.GetString("Sign")

	if loginName != "" && userName !="" && phone !="" && sign !="" {
		//对数据验签
		key, err1 := base64.StdEncoding.DecodeString(beego.AppConfig.String("sign_key"))
		if err1 != nil {
			log.Error(err1)
		}
		arr := []string{loginName, userName, phone}
		checkData := strings.Join(arr, ",")
		//先计算MD5再加密
		encryptData, _ := util.DesEncrypt(util.GetStringMd5(checkData), key)
		fmt.Println("encryptData=",hex.EncodeToString(encryptData))
		if strings.EqualFold(hex.EncodeToString(encryptData), sign) {
		    // save mysql
		    userDataModel := &models.UserDataModel{}
		    userDataModel.LoginName=loginName
		    userDataModel.UserName=userName
		    userDataModel.Phone=phone
		    var err,_ = dao.InsertUserData(userDataModel)
		    if err != nil {
			   rspm[constant.RSP_CODE] = constant.APP_RSP_FAIL
			   rspm[constant.RSP_INFO] ="数据保存失败"
			   //fmt.Println("数据保存失败")
		    }else{
		       rspm[constant.RSP_CODE] = constant.APP_RSP_SUCCESS
		       rspm[constant.RSP_INFO] = "数据保存成功"
		      //fmt.Println("数据保存成功")
		    }
		}else{
			rspm[constant.RSP_CODE] = constant.APP_RSP_FAIL
			rspm[constant.RSP_INFO] ="数据验签失败"
		}
	} else {
		rspm[constant.RSP_CODE] = constant.APP_RSP_FAIL
		rspm[constant.RSP_INFO] ="参数不能为空"
		//fmt.Println("参数不能为空")
	}
	c.Data["json"]=rspm
	c.Ctx.Output.SetStatus(200)
	c.ServeJSON()
}
